import sys
import os
import base64
import numpy as np
import cv2
import requests
import queue
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
                             QLabel, QVBoxLayout, QHBoxLayout, QWidget)
from PyQt5.QtGui import QPixmap, QImage, QPalette, QColor
from PyQt5.QtCore import Qt, QTimer
from hqyj_mqtt import Mqtt_Clt  # 导入MQTT客户端类


class RealtimeImageUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.api_url = "http://127.0.0.1:8080/process-image"
        self.is_realtime = False

        # 初始化MQTT客户端
        self.mqtt_queue = queue.Queue(5)
        self.mqtt_client = Mqtt_Clt(
            ip_broker='127.0.0.1',
            port_broker=21883,
            topic_sub='bb',
            topic_pub='aa',
            time_out_secs=60
        )

        # 初始化定时器用于图像处理
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.process_image)
        self.timer.setInterval(30)  # 约33fps，与原线程中的延迟保持一致

        # 创建请求会话
        self.req_session = requests.Session()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("智能驾驶系统")
        self.setGeometry(100, 100, 1000, 800)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(240, 248, 240))
        central_widget.setPalette(palette)
        central_widget.setAutoFillBackground(True)

        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)  # 增加内边距，视觉更舒展
        main_layout.setSpacing(15)  # 调整组件间距

        self.image_label = QLabel("等待启动实时模式...")
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setMinimumSize(800, 600)

        self.image_label.setStyleSheet("""
            QLabel {
                border: 2px solid #2E8B57; 
                background-color: #F8FFF8; 
                color: #235937;  /* 文字色：深绿色，与边框呼应 */
                font-size: 16px;
                font-weight: 500;
            }
        """)
        main_layout.addWidget(self.image_label)

        self.status_label = QLabel("状态: 未启动")

        self.status_label.setStyleSheet("""
            QLabel {
                color: #1E5631; 
                background-color: #E8F5E9; 
                padding: 8px 15px; 
                border-radius: 8px;  /* 圆角优化视觉 */
                font-size: 14px;
                border: 1px solid #A5D6A7;  /* 浅绿边框 */
            }
        """)
        main_layout.addWidget(self.status_label)

        btn_layout = QHBoxLayout()
        btn_layout.setContentsMargins(0, 0, 0, 10)

        self.toggle_btn = QPushButton("启动实时显示")
        self.toggle_btn.setMinimumHeight(45)
        self.toggle_btn.setMinimumWidth(180)

        self.toggle_btn.setStyleSheet("""
            QPushButton {
                background-color: #81C784;  /* 浅绿背景 */
                color: #1B5E20;  /* 深绿文字 */
                border: none;
                border-radius: 8px;
                font-size: 15px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #4CAF50;  /* 深绿背景（hover效果） */
                color: white;  /* 白色文字 */
            }
            QPushButton:pressed {
                background-color: #388E3C;  /* 暗绿背景（按下效果） */
            }
        """)
        self.toggle_btn.clicked.connect(self.toggle_realtime)
        btn_layout.addWidget(self.toggle_btn)

        main_layout.addLayout(btn_layout)

    def toggle_realtime(self):
        if not self.is_realtime:
            self.is_realtime = True
            self.toggle_btn.setText("停止实时显示")
            self.timer.start()  # 启动定时器
            self.update_status("状态: 运行中")
        else:
            self.is_realtime = False
            self.toggle_btn.setText("启动实时显示")
            self.timer.stop()  # 停止定时器
            self.update_status("状态: 已停止")
            self.image_label.setText("实时模式已停止")

    def process_image(self):
        """在主线程中处理图像，由定时器触发"""
        if not self.mqtt_client.mqtt_queue.empty():
            image_data = self.mqtt_client.mqtt_queue.get()
            if 'image' in image_data:
                self.update_status("处理图像中...")

                # 发送图像到API处理
                try:
                    response = self.req_session.post(
                        self.api_url,
                        json={"image": image_data['image']},
                        timeout=5
                    )
                    result = response.json()

                    if result.get("status") == "success" and "result" in result:
                        # 解码处理后的图像
                        result_bytes = base64.b64decode(result["result"])
                        result_np = np.frombuffer(result_bytes, dtype=np.uint8)
                        result_img = cv2.imdecode(result_np, cv2.IMREAD_COLOR)
                        if result_img is not None:
                            self.update_image(result_img)
                            self.update_status("图像已更新")
                except Exception as e:
                    self.update_status(f"处理出错: {str(e)}")

    def update_image(self, cv_image):
        # 转换颜色空间并显示
        rgb_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
        height, width, channel = rgb_image.shape
        bytes_per_line = channel * width
        q_image = QImage(rgb_image.data, width, height, bytes_per_line, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(q_image).scaled(
            self.image_label.width(),
            self.image_label.height(),
            Qt.KeepAspectRatio,
            Qt.SmoothTransformation
        )
        self.image_label.setPixmap(pixmap)

    def update_status(self, message):
        self.status_label.setText(message)

    def closeEvent(self, event):
        self.timer.stop()  # 停止定时器
        del self.mqtt_client
        event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = RealtimeImageUI()
    window.show()
    sys.exit(app.exec_())
